//展示登录框
function showLogin(){
    $("#login").fadeIn()
}

//是否已经登录
function hasLogin(){
    return Cookies.get('phone')
}

//绑定登录按钮
function bindLoginButton(){
    $("#loginBtn").click(function(){
        var name = $("#name").val() ;
        if(!name|| name.length > 8){
            return alert("姓名长度过长")
        }
        var phone = $("#phone").val();
        if(!/\d+/.test(phone) || phone.length != 13){
            return alert("电话号码错误！")
        }
        $.get("/index.php?r=coupon/login&tel="+phone+"&name="+name, function(data){
            if(data.code+"" == "2"){
               $("#login").fadeOut()
               Cookies.set('phone', phone)
            }else{
                $("#login").fadeIn()
            }
        })
    })
}

function showModel(id){
    $("#"+id).fadeIn()
}

function getYaoYiYaoResult(){
    var alertModel = ["", "login", "warn", "max", "win"]
    $.get("/index.php?r=coupon/wobble&tel="+ Cookies.get('phone'), function(data){
        var code = ~~data.code;
        if(code!=5){
            showModel(alertModel[code])
        }else{
            if(Math.random() * 100 > 50){
                showModel("fail_1")
            }else{
                showModel("fail_2")
            }
        }
    })
}

function bindYaoYiYaoAction(){
    //判断系统是否支持html5摇一摇的相关属性
    if (window.DeviceMotionEvent){
        var speed = 25;
        var x = t = z = lastX = lastY = lastZ = 0;
        var hasDo = false
        window.addEventListener('devicemotion',function () {
            if(!hasLogin()){
                return
            }
            if(hasDo){return}
            var acceleration = event.accelerationIncludingGravity;
            x = acceleration.x;
            y = acceleration.y;
            if (Math.abs(x - lastX) > speed || Math.abs(y - lastY) > speed) {
                hasDo = true
                setTimeout(function(){
                    hasDo = false
                },3000)  

            }
            lastX = x;
            lastY = y;
        }, false)
    }else{
        console.log("不支持摇一摇")
    }
}

$(function(){
    bindLoginButton()
    bindYaoYiYaoAction()
    var phone = Cookies.get('phone');
    if(!phone){
        return showLogin()
    }

})
